/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * A class that contains information about readiness
 * 
 * 
 */
public class Readiness implements BotObject {
   /**
    * Gets the readiness status for the specified readiness type
    * 
    * @param type
    * @return a Readiness object. Returns null if no readiness is found
    */
   public static Readiness getReadiness(final String type) {
	  Readiness out = null;
	  if (StringTools.isNullOrEmpty(type))
		 return out;
	  if (!isReadinessType(type))
		 return out;
	  if (!readinessIsActive(type))
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 List<String> unregistered = new LinkedList<String>();
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM kdprovince");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			unregistered.add(rs.getString("mainnick"));
		 }

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM " + "readiness WHERE done = false AND readinesstype = ?");
		 ps.setString(1, type);
		 rs = ps.executeQuery();

		 List<String> waiting = new LinkedList<String>();
		 while (rs.next()) {
			waiting.add(rs.getString("mainnick"));
			unregistered.remove(rs.getString("mainnick"));
		 }

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM " + "readiness WHERE done = true AND readinesstype = ?");
		 ps.setString(1, type);
		 rs = ps.executeQuery();

		 List<String> done = new LinkedList<String>();
		 while (rs.next()) {
			done.add(rs.getString("mainnick"));
			unregistered.remove(rs.getString("mainnick"));
		 }

		 out = new Readiness(type, done, waiting, unregistered);
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Checks whether the specified type is a recognized readiness type
    * 
    * @param type
    * @return true if the supplied type is a recognized readiness type
    */
   public static boolean isReadinessType(final String type) {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(type))
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM readinesslist WHERE readinesstype = ?");
		 ps.setString(1, type);
		 rs = ps.executeQuery();
		 out = rs.next();
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Checks whether the specified readiness type is active
    * 
    * @param type
    * @return true if the readiness type is active
    */
   public static boolean readinessIsActive(final String type) {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(type))
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM readinesslist WHERE readinesstype = ?");
		 ps.setString(1, type);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			out = rs.getBoolean("active");
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String readinessType = "";

   private List<String> done = new LinkedList<String>();

   private List<String> waiting = new LinkedList<String>();

   private List<String> unregistered = new LinkedList<String>();

   public Readiness(final String readinessType, final List<String> done, final List<String> waiting,
		 final List<String> unregistered) {
	  this.readinessType = readinessType;
	  this.done = done;
	  this.waiting = waiting;
	  this.unregistered = unregistered;
   }

   public List<String> getDone() {
	  return done;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getReadinessType()) || getDone() == null || getWaiting() == null || getUnregistered() == null)
		 return out;
	  String output = Colors.OLIVE + "Waiting players: " + Colors.BLUE;
	  for (String player : getWaiting()) {
		 if (output.length() > 300) {
			out.add(output);
			output = "";
		 }
		 output += Colors.BLUE + player + Colors.NORMAL + ", ";
	  }
	  if (output.length() > 1) {
		 out.add(output);
	  }

	  output = Colors.DARK_GREEN + "Done players: " + Colors.BLUE;
	  for (String player : getDone()) {
		 if (output.length() > 300) {
			out.add(output);
			output = "";
		 }
		 output += Colors.BLUE + player + Colors.NORMAL + ", ";
	  }
	  if (output.length() > 1) {
		 out.add(output);
	  }

	  if (!getUnregistered().isEmpty()) {
		 output = Colors.RED + "Unregistered players: " + Colors.BLUE;
		 for (String player : getUnregistered()) {
			if (output.length() > 300) {
			   out.add(output);
			   output = "";
			}
			output += Colors.BLUE + player + Colors.NORMAL + ", ";
		 }
		 if (output.length() > 1) {
			out.add(output);
		 }
	  }
	  return out;
   }

   public String getReadinessType() {
	  return readinessType;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getReadinessType()) || getDone() == null || getWaiting() == null || getUnregistered() == null)
		 return out;
	  out.put("Readiness Type", getReadinessType());
	  out.put("Done", getDone());
	  out.put("Waiting", getWaiting());
	  out.put("Unregistered", getUnregistered());
	  return out;
   }

   public List<String> getUnregistered() {
	  return unregistered;
   }

   public List<String> getWaiting() {
	  return waiting;
   }

   @Override
   public boolean saveToDB() {
	  return false;
   }
}
